package com.surprise.base.util;

/**
 * SafetyUtils
 * @author nick
 * 2014年9月11日
 */
public class SafetyUtils {
    public static boolean isSafe(String sign, Object... keyvalues) {
        if (keyvalues.length == 0 || keyvalues.length % 2 == 1) {
            return false;
        }
        String md5 = genMd5(keyvalues);
        return sign.equals(md5);
    }

    public static String genMd5(Object... keyvalues) {
        StringBuilder sb = new StringBuilder();
        String template = "%s:%s";
        char delim = ',';
        int length = keyvalues.length / 2;

        for (int i = 0; i < length; ++i) {
            sb.append(String.format(template, new Object[] {
                    keyvalues[i * 2], keyvalues[i * 2 + 1]
            })).append(delim);
        }
        sb.deleteCharAt(sb.lastIndexOf(","));
        return Md5Utils.md5(sb.toString());
    }
}
